package cn.edu.sjtu.permission;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cn.edu.sjtu.DedexerPlus;

public class CPPermissionChecker extends PermissionChecker {

	public CPPermissionChecker(String path) {
		super(path);
	}

	public void checkPermission(DedexerPlus ddxp) {
		if (cSet.size() > 0) {
			Iterator it = cSet.iterator();
        	while (it.hasNext()) {
        		String[] sa = ((String )it.next()).split("@");
        		ddxp.getRegValueToCheck(sa[0], Long.parseLong(sa[1]), Integer.parseInt(sa[2]), sa[3], sa[4], 0, this);
        	}
		}
	}
	
	public void analyse(HashSet<String> pset, String func, String regValue) {
		String pre = null;
		if (func.contains(".query")) {
			pre = "read:";
		} else if (func.contains(".insert")) {
			pre = "write:";
		} else if (func.contains(".update")) {
			pre = "update:";
		} else {
			pre = "delete:";
		}
		int i = 0, j = 0;
		while (i < regValue.length()) {
			i = regValue.indexOf("content://", i);
			j = regValue.indexOf("\"", i + 10);
			if (i == -1 || j == -1)	break;
			String uri = regValue.substring(i, j);
			uri = pre + uri;
			if (pMap.containsKey(uri)) {
				setPermissionSet(pset, pMap.get(uri));
				System.out.println("App require CP: " + pMap.get(uri));
			}
			uri = pre + "content://com.android." + regValue.substring(i + 10, j);
			if (pMap.containsKey(uri)) {
				setPermissionSet(pset, pMap.get(uri));
				System.out.println("App require CP: " + uri + " " + pMap.get(uri));
			}
			
			i = j + 1;
		}
	}
	
    protected void setPermissionMap(String path, HashMap<String, String> map) {
    	try {
			XSSFWorkbook xwb = new XSSFWorkbook(path);
			XSSFSheet sheet = xwb.getSheetAt(0);
			XSSFRow row;
			for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
				row = sheet.getRow(i);
				if (row != null && row.getCell(0) != null
						&& !row.getCell(0).equals("")) {
					map.put(row.getCell(0).toString() + ":"
							+ row.getCell(1).toString(), row.getCell(2)
							.toString());
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
